package com.wangshb.upms.core.utils;

import com.alibaba.fastjson.JSONObject;
import com.wangshb.upms.core.common.GpResponse;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * HTTP工具类
 * @author Louis
 * @date Jun 29, 2019
 */
public class HttpUtils {

	/**
	 * 获取HttpServletRequest对象
	 * @return
	 */
	public static HttpServletRequest getHttpServletRequest() {
		return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
	}
	
	/**
	 * 输出信息到浏览器
	 * @param response
	 * @throws IOException
	 */
	public static void write(HttpServletResponse response, GpResponse gpResponse) throws IOException {
		response.setContentType("application/json; charset=utf-8");
        String json = JSONObject.toJSONString(gpResponse);
        response.getWriter().print(json);
        response.getWriter().flush();
        response.getWriter().close();
	}


	/**
	 *  判断是否为ajax请求
	 */
	public static boolean isAjaxRequest(HttpServletRequest request) {
		if (request.getHeader("accept").indexOf("application/json") > -1
				|| (request.getHeader("X-Requested-With") != null && request.getHeader("X-Requested-With").equals(
				"XMLHttpRequest"))) {
			return true;
		}
		return false;
	}
}
